package com.ruoyi.business.controller.redis;

/**
 * @author Wu Yuwei
 * @Description:
 * @date 2022/11/9 14:34
 */
public class RedisLuaScript {

    /**
     * 1. 判断key[1]是否存在
     * 2. 不存在返回null
     * 3. 存在自增key[1],increment为ARGV[1]
     */
    public static final String INCR_BY_SCRIPT = "local e=redis.call('EXISTS',KEYS[1])\n" +
            "if e == 0 then\n" +
            "   return ''\n" +
            "end\n" +
            "return redis.call('INCRBY',KEYS[1], ARGV[1])";

    /**
     * 设置key[1]的值为ARGV[1],缓存时间至ARGV[2]
     */
    public static final String INIT_SCRIPT = "redis.call('SET', KEYS[1], ARGV[1])\n" +
            "redis.call('EXPIREAT', KEYS[1], ARGV[2])";

    /**
     * 1. 判断key[1]是否存在
     * 2. 不存在返回null
     * 3. 存在自增key[1],increment为ARGV[1]
     * 4. 如果自增结果大于ARGV[2]，则对key[1]的值进行还原，并返回0
     * 5. 反之如果自增结果小于等于ARGV[2]，则返回1
     */
    public static final String INCR_BY_LIMIT_SCRIPT = "local e=redis.call('EXISTS',KEYS[1])\n" +
            "if e == 0 then\n" +
            "   return ''\n" +
            "end\n" +
            "local v = redis.call('INCRBY',KEYS[1], ARGV[1])\n" +
            "if tonumber(v) > tonumber(ARGV[2]) then\n" +
            "   redis.call('INCRBY',KEYS[1], -ARGV[1])\n" +
            "   return '0'\n" +
            "else\n" +
            "   return '1'\n" +
            "end";

}
